package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapLikeType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IMemberService;
import com.mall.user.IUserLoginService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference(timeout = 30000,check = false)
    IKaptchaService iKaptchaService;

    @Reference(timeout = 30000,check = false)
    IUserLoginService iUserLoginService;

    //用户登录
    @PostMapping("/login")
    @Anoymous
    public ResponseData loginPost(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse resp){
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(userName);
        userLoginRequest.setPassword(userPwd);
        //判断图形验证码是否正确
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        //校验登录验证码是否正确,不正确返回异常信息，正确就继续执行
        if(!validateCode(kaptchaCodeRequest)){
            return new ResponseUtil<>().setErrorMsg(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());
        }
        //进入数据库中查询用户信息
        UserLoginResponse response = iUserLoginService.login(userLoginRequest);
        if(!SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        //登录成功,设置cookie
        Cookie cookie = CookieUtil.genCookie("access_token", response.getToken(), "/", 60*60);
        cookie.setHttpOnly(true);
        resp.addCookie(cookie);
        return new ResponseUtil<>().setData(response);
    }


    /**
     * 校验验证码输入是否正确
     * @param request
     * @return true代表正确,false代表错误
     */
    private boolean validateCode(KaptchaCodeRequest request) {
        KaptchaCodeResponse response = iKaptchaService.validateKaptchaCode(request);
        return SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode());
    }

    @GetMapping("/login")
    public ResponseData loginGet(HttpServletRequest request){
        String attribute = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        try {
//            attribute = attribute.replaceAll("\\\\", "");
//            attribute = attribute.substring(1, attribute.length() - 1);
            JSONObject map = JSON.parseObject(attribute);
            return new ResponseUtil<>().setData(map);
        }catch (Exception e){
           return new ResponseUtil<>().setErrorMsg("token已失效");
        }
    }

    @RequestMapping("/register")
    @Anoymous
    public ResponseData register(@RequestBody Map<String,String> map,HttpServletRequest request){
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");
        //判断图形验证码是否正确
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest(uuid,captcha);
        //校验登录验证码是否正确,不正确返回异常信息，正确就继续执行
        if(!validateCode(kaptchaCodeRequest)){
            return new ResponseUtil<>().setErrorMsg(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());
        }
        //注册业务
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest(userName,userPwd,email);
        UserRegisterResponse response = iUserLoginService.register(userRegisterRequest);
        if(!SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(null);
    }

    @RequestMapping("/verify")
    @Anoymous
    public ResponseData verify(UserVerifyRequest request){
        UserVerifyResponse response = iUserLoginService.verify(request);
        if(!SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(null);
    }
    @RequestMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if("access_token".equals(cookie.getName())) {
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return new ResponseUtil<>().setData(null);
    }
}
